package com.example.restatr.Atcivity.PetHospital;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.PetHospital.Bean.CasesConsultationBean;
import com.example.restatr.Atcivity.PetHospital.Bean.InquiryBean;
import com.example.restatr.Atcivity.PetHospital.Bean.PawsClawsPetVetBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PetDoctorDetailsAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private ImageView head;
    private TextView name;
    private TextView workStartAt;
    private TextView serviceTimes;
    private TextView legalExpertiseName;
    private TextView baseInfo;
    private RecyclerView rv;
    private LinearLayout Null;
    private TextView nullText;
    private LinearLayout loading;
    private CardView btn;
    private PawsClawsPetVetBean.RowsBean data;
    private List<CasesConsultationBean.RowsBean> casesBeans = new ArrayList<>();
    private RelativeLayout pl;
    private EditText plEdText;
    private MaterialButton button;
    private int inquiryId, pos;
    private adapter adapter = new adapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_pet_doctor_details_at );
        bindView();
        Tools.SetBarTitle( toolbar, barTitle, "详细信息", search, this, false );
        data = new Gson().fromJson( getIntent().getStringExtra( "data" ), PawsClawsPetVetBean.RowsBean.class );
        Glide.with( this )
                .load( Tools.ip + data.getAvatar() )
                .transform( new CircleCrop() )
                .into( head );
        name.setText( data.getName() );
        workStartAt.setText( "职业证号：" + data.getPracticeNo() );
        serviceTimes.setText( "从业时间：" + data.getWorkingYears() + "年" );
        legalExpertiseName.setText( data.getJobName() );
        nullText.setText( "暂无问诊记录..." );
        baseInfo.setText( data.getGoodAt() );
        GetAllCases();
        plEdText.setHint( "写下您的问题吧！~" );
        plEdText.addTextChangedListener( new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!plEdText.getText().toString().trim().isEmpty()) {
                    button.setVisibility( View.VISIBLE );
                } else {
                    button.setVisibility( View.GONE );
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        } );
        //评论提交按钮
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inquiryMessage();
            }


        } );
    }

    //追问聊天
    private void inquiryMessage() {
        new Thread( () -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put( "inquiryId", inquiryId );
                jsonObject.put( "content", plEdText.getText().toString() );
                String token = Tools.Post( "/prod-api/api/pet-hospital/inquiry-message",
                        MainActivity.sp.getString( "token", "" ), jsonObject.toString() );
                JSONObject jx = new JSONObject( token );
                String msg = jx.getString( "msg" );
                int code = jx.getInt( "code" );
                runOnUiThread( () -> {
                    Toast.makeText( this, msg, Toast.LENGTH_SHORT ).show();
                    if (code == 200) {
                        plEdText.setText( "" );
                        pl.setVisibility( View.GONE );
                        btn.setVisibility( View.VISIBLE );
                        adapter.notifyItemChanged( pos );
                    }
                } );
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } ).start();
    }

    //获取当前医生问诊案例
    private void GetAllCases() {
        new Thread( () -> {
            String token = Tools.Get( "/prod-api/api/pet-hospital/inquiry/list?doctorId=" +
                    data.getId(), MainActivity.sp.getString( "token", "" ) );
            CasesConsultationBean casesConsultationBean = new Gson().fromJson( token, CasesConsultationBean.class );
            casesBeans.addAll( casesConsultationBean.getRows() );
            runOnUiThread( () -> {
                loading.setVisibility( View.GONE );
                if (casesBeans.size() > 0) {
                    rv.setAdapter( adapter );
                } else {
                    Null.setVisibility( View.VISIBLE );
                }
            } );
        } ).start();
    }

    //获取某个问诊中的所有聊天
    private void GetQuestion(int id, CardView card, RecyclerView rv) {
        new Thread( () -> {
            String token = Tools.Get( "/prod-api/api/pet-hospital/inquiry-message/list?inquiryId=" + id, MainActivity.sp.getString( "token", "" ) );
            InquiryBean inquiryBean = new Gson().fromJson( token, InquiryBean.class );
            List<InquiryBean.RowsBean> inquiryRows = new ArrayList<>();
            inquiryRows.addAll( inquiryBean.getRows() );
            runOnUiThread( () -> {
                if (inquiryRows.size() > 0) {
                    card.setVisibility( View.VISIBLE );
                    rv.setAdapter( new inquiryAdapter( inquiryRows ) );
                }
            } );
        } ).start();
    }

    private void bindView() {
        toolbar = findViewById( R.id.toolbar );
        barTitle = findViewById( R.id.bar_Title );
        search = findViewById( R.id.search );
        head = findViewById( R.id.head );
        name = findViewById( R.id.name );
        workStartAt = findViewById( R.id.workStartAt );
        serviceTimes = findViewById( R.id.serviceTimes );
        legalExpertiseName = findViewById( R.id.legalExpertiseName );
        baseInfo = findViewById( R.id.baseInfo );
        rv = findViewById( R.id.rv );
        Null = findViewById( R.id.Null );
        nullText = findViewById( R.id.null_text );
        loading = findViewById( R.id.loading );
        btn = findViewById( R.id.btn );
        pl = findViewById( R.id.pl );
        plEdText = findViewById( R.id.pl_edText );
        button = findViewById( R.id.button );
    }

    public void onClick(View view) {
        Intent intent = new Intent( PetDoctorDetailsAt.this, CreateConsultingAt.class );
        intent.putExtra( "id", data.getId() );
        startActivity( intent );
    }

    class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
        class viewHolder extends RecyclerView.ViewHolder {
            private LinearLayout ll2;
            private TextView title;
            private TextView undertaker;
            private TextView content;
            private ImageView img;
            private CardView cardRv;
            private RecyclerView rv2;

            public viewHolder(@NonNull View itemView) {
                super( itemView );
                ll2 = itemView.findViewById( R.id.ll2 );
                title = itemView.findViewById( R.id.title );
                undertaker = itemView.findViewById( R.id.undertaker );
                name = itemView.findViewById( R.id.name );
                content = itemView.findViewById( R.id.content );
                img = itemView.findViewById( R.id.img );
                cardRv = itemView.findViewById( R.id.cardRv );
                rv2 = itemView.findViewById( R.id.rv );
            }
        }

        @NonNull
        @Override
        public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate( R.layout.service_info_item, parent, false );
            return new viewHolder( inflate );
        }

        @Override
        public void onBindViewHolder(@NonNull viewHolder holder, int position) {
            holder.title.setText( "用户" + casesBeans.get( position ).getUserId() );
            holder.undertaker.setText( casesBeans.get( position ).getCreateTime().substring( 0, 10 ) );
            holder.ll2.setVisibility( View.GONE );
            if (casesBeans.get( position ).getQuestion() != null && !casesBeans.get( position ).getQuestion().trim().isEmpty()) {
                holder.content.setText( casesBeans.get( position ).getQuestion() );
            } else {
                holder.content.setText( "暂无问题！" );
            }
            Glide.with( PetDoctorDetailsAt.this )
                    .load( Tools.ip + casesBeans.get( position ).getImageUrls() )
                    .transform( new RoundedCorners( 15 ) )
                    .listener( new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Drawable> target, boolean b) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable drawable, Object o, Target<Drawable> target, DataSource dataSource, boolean b) {
                            holder.img.setImageDrawable( drawable );
                            holder.img.setVisibility( View.VISIBLE );
                            return true;
                        }
                    } )
                    .into( holder.img );

            GetQuestion( casesBeans.get( position ).getId(), holder.cardRv, holder.rv2 );
            holder.itemView.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btn.setVisibility( View.GONE );
                    pl.setVisibility( View.VISIBLE );
                    inquiryId = casesBeans.get( position ).getId();
                    pos = position;
                }
            } );
        }

        @Override
        public int getItemCount() {
            return casesBeans.size();
        }

    }

    class inquiryAdapter extends RecyclerView.Adapter<inquiryAdapter.viewHolder> {
        private List<InquiryBean.RowsBean> list;

        public inquiryAdapter(List<InquiryBean.RowsBean> list) {
            this.list = list;
        }

        @NonNull
        @Override
        public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate( R.layout.service_info_item, parent, false );
            return new viewHolder( inflate );
        }

        @Override
        public void onBindViewHolder(@NonNull viewHolder holder, int position) {
            holder.title.setText( "用户" + list.get( position ).getFromId() );
            holder.content.setText( list.get( position ).getContent() );
            holder.undertaker.setText( list.get( position ).getCreateTime().substring( 0, 10 ) );
            holder.ll2.setVisibility( View.GONE );
            if (list.get( position ).getFromRole().equals( "1" )) {
                holder.title.setText( data.getName() + "医生" );
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class viewHolder extends RecyclerView.ViewHolder {
            private TextView title;
            private TextView undertaker;
            private TextView content;
            private LinearLayout ll2;

            public viewHolder(@NonNull View itemView) {
                super( itemView );
                title = itemView.findViewById( R.id.title );
                undertaker = itemView.findViewById( R.id.undertaker );
                content = itemView.findViewById( R.id.content );
                ll2 = itemView.findViewById( R.id.ll2 );
            }
        }
    }

}